﻿<%@ WebHandler Language="C#" Class="cert" %>

using System;
using System.Web;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;
using System.IO;
using System.Data;
using System.Text.RegularExpressions;

public class cert : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/json";
        string opt = HttpContext.Current.Request.Params["opt"]; //操作下载download ，打印print
       
        string data_batch = HttpContext.Current.Request.Params["data_batch[]"]; //批号
        string ids = HttpContext.Current.Request.Params["ids[]"];             //商品ID+|+批号
        string data_optio = HttpContext.Current.Request.Params["data_optio"]; //文件类型

  
      

        if (opt == "download")
        {
            context.Response.Write("{\"code\": 1, \"url\": \"/search/cert.ashx?opt=zip&ids[]=" + ids + "&data_batch=" + data_batch + "&data_optio=" + data_optio + "\"}");
        }
         if (opt == "print")
        {
            context.Response.Write("{\"code\":1,\"msg\":\"\u6253\u5370\u6587\u6863\u83b7\u53d6\u6210\u529f\",\"url\":[" + print(ids, data_optio) + "],\"info\":\"" + data_optio + "\"}");
        }
         if (opt == "zip")
         {
             //context.Response.Write("{\"code\":1,\"msg\":\"\u6253\u5370\u6587\u6863\u83b7\u53d6\u6210\u529f\",\"url\":[\"\"],\"info\":\"" + DataBase(ids) + "\"}");
             download(DataBase(ids));
         }
    }
    Common Init = new Common();
    MsSqlHelper mssql = new MsSqlHelper();
    DataTable dt;
    public string typename = "";
    
    
    public string DataBase(string ids)
    {
        string sql = "";
        string imageid = "";
        string[] sArray = ids.Split(',');

        foreach (string i in sArray)
        {

            string[] nArray = i.ToString().Split('|');
            string spid = nArray[0].ToString();
            string data_optio = nArray[1].ToString();
            

            sql = "select distinct rtrim(a.imageid) as imageid from [ImageDoc] a(nolock),spkfk b(nolock) where b.spid=a.detailid and b.spid='" + spid + "'";
            switch (data_optio)
            {
                case "quanbu":
                    sql += " and a.type_id in('zc','pj','bz','sm','rf','pf','sf')";
                    break;
                case "bg":
                    sql += " and a.type_id='bg'";
                    break;
                case "pj":
                    sql += " and a.type_id='pj'";
                    break;
                case "cj":
                    sql += " and a.type_id='cj'";
                    break;
                case "sm":
                    sql += " and a.type_id='sm'";
                    break;
                case "bz":
                    sql += " and a.type_id='bz'";
                    break;
                case "sf":
                    sql += " and a.type_id='sf'";
                    break;
                case "pf":
                    sql += " and a.type_id='pf'";
                    break;
                case "rf":
                    sql += " and a.type_id='rf'";
                    break;
                case "iquanbu":
                    sql += " and a.type_id in('fa','sh','ghssh','ghsfa','rk')";
                    break;
                case "fa":
                    sql += " and a.type_id='fa'";
                    break;
                case "sh":
                    sql += " and a.type_id='sh'";
                    break;
                case "ghssh":
                    sql += " and a.type_id='ghssh'";
                    break;
                case "ghsfa":
                    sql += " and a.type_id='ghsfa'";
                    break;
                case "rk":
                    sql += " and a.type_id='rk'";
                    break;
                default:
                    sql += " and 1=2";
                    break;
            }
            dt = mssql.ExecuteDt(sql);
            for (int n = 0; n < dt.Rows.Count; n++)
            {
                imageid += dt.Rows[n]["imageid"].ToString() + ",";
            }
        }
        return imageid;
    }

    /// <summary>
    /// 预览JSON组装
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    public string print(string ids,string data_optio)
    {
        string idsx=DataBase(ids);
        string[] sArray = idsx.Split(',');
        string url = "";
        string sql = "";
        foreach (string i in sArray)
        {
           sql = "select rtrim(url) url from [ImageDoc](nolock) where  imageid ='" + i.ToString() + "'";                         
            
            DataTable dt = mssql.ExecuteDt(sql);
            for (int n = 0; n < dt.Rows.Count; n++)
            {
                url += "\"" + dt.Rows[n]["url"].ToString() + "\",";
            }
        }
        if (url.IndexOf(",") > 0)
        {
            url = url.Remove(url.Length - 1, 1);
        }
        return url;
    }
    /// <summary>
    ///下载 组装
    /// </summary>
    /// <param name="ids"></param>
    public void download(string ids)
    {
        ZipFileByCode(ids);
    }


    /// <summary>
    /// 压缩打包文件
    /// </summary>
    /// <param name="ids">ids格式：url\新名字,url\新名字,...</param>
    public void ZipFileByCode(string ids)
    {
        string sql = "";
        string test = "";
        try
        {
            string content = "\r\n\r\n"+Init.EntName+"\r\n\r\n\r\n质量管理部 联系方式：\r\n    联系电话：028-83420470\r\n    质量反馈QQ：2850897874\r\n    检验报告接收QQ：2850897881\r\n    检验报告查找QQ：2850519828\r\n\r\n图片资料打包\r\nCopyright © 2018 Sitaier QQ:613329777 All rights reserved";
            if (ids.Length != 0)
            {
                string[] sArray = ids.Split(',');

                MemoryStream ms = new MemoryStream();
                byte[] buffer = null;

                using (ZipFile file = ZipFile.Create(ms))
                {
                    file.BeginUpdate();
                    file.NameTransform = new MyNameTransfom();//通过这个名称格式化器，可以将里面的文件名进行一些处理。默认情况下，会自动根据文件的路径在zip中创建有关的文件夹。
                    file.SetComment(content);
                    foreach (string i in sArray)
                    {
                        DataTable dt = new DataTable();
                        sql = "select distinct rtrim(url) url,rtrim(imageid) plh,rtrim(c.spmch) as spmch,rtrim(b.extend) as extend,rtrim(type_id) type_id,rtrim(b.leibie) as leibie,rtrim(b.fzxx1) as pihao"
                           + " from [ImageDoc] b(nolock),spkfk c(nolock) where c.spid=b.detailid and b.imageid ='" + i.ToString() + "'";
                        
                        dt = mssql.ExecuteDt(sql);

                        for (int n = 0; n < dt.Rows.Count; n++)
                        {
							if (File.Exists("H:\\" + dt.Rows[n]["url"].ToString().Replace("Upload","TuPian")))
                            {
                                //file.Add("H:\\" + dt.Rows[n]["url"].ToString(), dt.Rows[n]["spmch"].ToString() + "_" + dt.Rows[n]["leibie"].ToString() + "_" + dt.Rows[n]["pihao"].ToString() + "_" + n + "_" + dt.Rows[n]["plh"].ToString() + dt.Rows[n]["extend"].ToString());
                                file.Add("H:\\" + dt.Rows[n]["url"].ToString().Replace("Upload","TuPian"), filer(dt.Rows[n]["spmch"].ToString()) + "_" + dt.Rows[n]["leibie"].ToString() + "_" + dt.Rows[n]["pihao"].ToString() + "_" + dt.Rows[n]["plh"].ToString() + dt.Rows[n]["extend"].ToString());
                            }
                            if (File.Exists(Init.imagefilepath(dt.Rows[n]["url"].ToString())))
                            {
                             file.Add(Init.imagefilepath(dt.Rows[n]["url"].ToString()), filer(dt.Rows[n]["spmch"].ToString()) + "_" + dt.Rows[n]["leibie"].ToString() + "_" + dt.Rows[n]["pihao"].ToString() + "_" + dt.Rows[n]["plh"].ToString() + dt.Rows[n]["extend"].ToString());   
                            }
                        }                        
                    }
                    //file.Add(AppDomain.CurrentDomain.BaseDirectory + "简介.docx");

                    file.CommitUpdate();
                    buffer = new byte[ms.Length];
                    ms.Position = 0;
                    ms.Read(buffer, 0, buffer.Length);
                }
                DateTime dts = DateTime.Now;
                HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=PIC" + dts.ToLocalTime().ToString() + ".zip");
                HttpContext.Current.Response.BinaryWrite(buffer);
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.End();
            }
        }
        catch (Exception ex)
        {
            HttpContext.Current.Response.Write("{\"code\":0,\"msg\":\"\u6ca1\u6709\u53ef\u4e0b\u8f7d\u6216\u6253\u5370\u7684\u6587\u6863||" + test + "||" + HttpContext.Current.Server.MapPath("~") + "||" + sql + "||" + ex.ToString() + "\"}");
        }
    }

    public void downloadx(string ids)
    {
        string[] sArray = ids.Split(',');
        string url = "";
        foreach (string i in sArray)
        {
            string sql = "select rtrim(url) url from spls_ck a(nolock),[ImageDoc] b(nolock) where a.spid=b.detailid and a.pihao=b.fzxx1 and a.plh ='" + i.ToString() + "' group by url";
            DataTable dt = mssql.ExecuteDt(sql);
            for (int n = 0; n < dt.Rows.Count; n++)
            {
                url += dt.Rows[n]["url"].ToString() + ",";
            }
        }
        if (url.IndexOf(",") > 0)
        {
            url = url.Remove(url.Length - 1, 1);
        }
        ZipFileByCodex(url);
    }

    /// <summary>
    /// 压缩打包文件
    /// </summary>
    /// <param name="ids"></param>
    public static void ZipFileByCodex(string ids)
    {
        if (ids.Length != 0)
        {
            MemoryStream ms = new MemoryStream();
            byte[] buffer = null;

            using (ZipFile file = ZipFile.Create(ms))
            {
                file.BeginUpdate();
                file.NameTransform = new MyNameTransfom();//通过这个名称格式化器，可以将里面的文件名进行一些处理。默认情况下，会自动根据文件的路径在zip中创建有关的文件夹。

                string[] sArray = ids.Split(',');
                foreach (string i in sArray)
                {
                    // file.Add(HttpContext.Current.Server.MapPath("~")+i.ToString(),);
                    file.Add(HttpContext.Current.Server.MapPath("~") + i.ToString());
                }
                file.CommitUpdate();

                buffer = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(buffer, 0, buffer.Length);
            }
            DateTime dt = DateTime.Now;
            System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=文档系统" + dt.ToLocalTime().ToString() + ".zip");
            System.Web.HttpContext.Current.Response.BinaryWrite(buffer);
            System.Web.HttpContext.Current.Response.Flush();
            System.Web.HttpContext.Current.Response.End();
        }
    }
    /// <summary>
    /// 
    /// </summary>
    public class MyNameTransfom : ICSharpCode.SharpZipLib.Core.INameTransform
    {

        #region INameTransform 成员

        public string TransformDirectory(string name)
        {
            return null;
        }

        public string TransformFile(string name)
        {
            return Path.GetFileName(name);
        }

        #endregion
    }
	
	public string filer(string str)
    {
        //string str = "a:b/c;d*e?f<g.txt";//文件名
        string reg = @"\:" + @"|\;" + @"|\/" + @"|\\" + @"|\|" + @"|\," + @"|\*" + @"|\?" + @"|\""" + @"|\<" + @"|\>";//特殊字符
        Regex r = new Regex(reg);
        string strFiltered = r.Replace(str, "：");//将特殊字符替换为""
        return strFiltered;
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}